#include "UdpServer.hpp"
#include "log.hpp"
#include <memory>
#include <vector>
using namespace std;
Log log;

void Usage(string proName)
{
    cout << "\n\rUsage: " << proName << " [大于1023的端口号]" << endl;
}

string handler(const string &info, const string &clientIP, const uint16_t &clientPort)
{
    cout << "[" << clientIP << ":" << clientPort << "]#" << info << endl;
    string res = "Server get a message: ";
    res += info;
    return res;
}

bool SafeCheck(const string &cmd)
{
    vector<string> words = {
        "rm",
        "mv",
        "cp",
        "kill",
        "unlink",
        "uninstall",
        "yum",
        "top",
        "while"};
    for (auto &word : words)
    {
        auto pos = cmd.find(word);
        if (pos != string::npos)
            return false;
    }
    return true;
}

string excuteCommand(const string &cmd)
{
    cout << "get a request cmd:" << cmd << endl;
    if (!SafeCheck(cmd))
        return "Bad man";
    FILE *fp = popen(cmd.c_str(), "r");
    if (fp == nullptr)
    {
        perror("popen");
        return "error";
    }
    string res;
    char buffer[4096];
    while (true)
    {
        char *ok = fgets(buffer, sizeof(buffer), fp);
        if (ok == nullptr)
            break;
        res += buffer;
    }
    pclose(fp);
    return res;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }
    uint16_t port = stoi(argv[1]);
    unique_ptr<UdpServer> svr(new UdpServer(port));
    svr->Init();
    svr->Run(handler);
    return 0;
}
